package kafka.newstyle;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class Producer {
    public static String topic = "test";//定义主题

    public static void main(String[] args) throws InterruptedException, FileNotFoundException {
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "niit-master:9092");//kafka地址，多个地址用逗号分割
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(p);

        String filePath = Producer.class.getClassLoader().getResource("data/app.log").getFile();
        File app = new File(filePath);
        InputStreamReader isr = new InputStreamReader(new FileInputStream(app), StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
        String lineTxt;

        try {
            while ((lineTxt = br.readLine()) != null) {
//                URL url2 = Producer.class.getResource("/");


//                String msg = "Hello," + new Random().nextInt(100);
                ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, lineTxt);
                kafkaProducer.send(record);
                System.out.println("消息发送成功:" + lineTxt);
                Thread.sleep(1000);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            kafkaProducer.close();
        }

    }
}
